// src/js/admin/school.js
import { ref, computed, reactive } from 'vue';
import "jbecool/jbecool.uniapp.min.js";
import VMControl from '@/js/VMControl';

// 创建基于 VMControl 的学校管理实例
const S = new VMControl('OBEvolutionAI.SchoolControl', 'schoolId');

// 学校数据列表（覆盖 VMControl 中的 modelList）
S.schools = ref([]);

// 根据搜索关键词过滤学校列表
S.filteredSchools = computed(() => {
    if (!S.searchKeyword.value) {
        return S.schools.value;
    }
    return S.schools.value.filter(school =>
        school.name.toLowerCase().includes(S.searchKeyword.value.toLowerCase())
    );
});

// 导航到学院管理
S.navigateToColleges = function (school) {
    uni.navigateTo({
        url: "/pages/admin/college-management?schoolId=" + school.schoolId,
    });
};

// 添加学校
S.handleAddSchool = () => {
    S.handleAdd();
};

// 编辑学校
S.handleEditSchool = (school) => {
    S.setCurrentModel(school);
    S.handleEdit();
};

// 删除学校
S.handleDeleteSchool = (school) => {
    uni.showModal({
        title: '确认删除',
        content: `确定要删除学校 "${school.name}" 吗？`,
        success: async function (res) {
            if (res.confirm) {
                const index = S.schools.value.findIndex(s => s.schoolId === school.schoolId);
                if (index !== -1) {
                    const im = await J.callApiAsync(
                        "OBEvolutionAI.SchoolControl.delete_by_id", { id: school.schoolId });
                    if (im.success) {
                        S.schools.value.splice(index, 1);
                        uni.showToast({ title: '删除成功', icon: 'success' });
                    } else {
                        console.error('删除失败:', im);
                    }
                }
            }
        }
    });
};

// 提交表单（添加或编辑）
S.handleSubmitSchool = async () => {
    if (S.modalMode.value === 'add') {
        const im = await J.callApiAsync(
            "OBEvolutionAI.SchoolControl.add", 
            { model: { ...S.currentModel } }
        );
        if (im.success) {
            S.schools.value.push(im.data);
            uni.showToast({ title: '添加成功', icon: 'success' });
            S.closePopup();
        } else {
            console.error('添加失败:', im);
            uni.showToast({ title: '添加失败: ' + im.msg, icon: 'none' });
        }
    } else {
        const im = await J.callApiAsync(
            "OBEvolutionAI.SchoolControl.update_by_id", {
                id: S.currentModel.schoolId,
                model: { ...S.currentModel }
            }
        );
        if (im.success) {
            const index = S.schools.value.findIndex(s => s.schoolId === S.currentModel.schoolId);
            if (index !== -1) {
                S.schools.value[index] = { ...S.currentModel };
            }
            uni.showToast({ title: '更新成功', icon: 'success' });
            S.closePopup();
        } else {
            console.error('更新失败:', im);
            uni.showToast({ title: '更新失败: ' + im.msg, icon: 'none' });
        }
    }
};

// 重写 handleSubmit 方法以使用我们的自定义方法
S.handleSubmit = S.handleSubmitSchool;

// 加载学校数据
S.loadSchools = async () => {
    const res = await J.callApiAsync("OBEvolutionAI.SchoolControl.get_list", {});
    if (res.success) {
        S.schools.value = res.data;
        S.filteredModels.value = S.schools.value;
    } else {
        console.error('加载学校数据失败:', res);
        S.schools.value = [];
        S.filteredModels.value = [];
        uni.showToast({ title: '加载数据失败', icon: 'none' });
    }
};

export default S;